<template>
  <div class="device-management-container">
    <!-- 顶部搜索与筛选 -->
    <el-card class="filter-card">
      <el-row :gutter="20">

<!--        <el-col :span="8">
          <el-input v-model="searchQuery" placeholder="搜索设备名称" clearable @clear="handleSearch">
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </el-col>-->

        <el-col :span="5">
          <el-select v-model="searchType" placeholder="选择搜索类型">
            <el-option label="按名称搜索" value="name"></el-option>
            <el-option label="按ID搜索" value="id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchQuery" placeholder="输入搜索内容" clearable @clear="handleSearch">
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </el-col>



        <el-col :span="3">
          <el-select v-model="statusFilter" placeholder="筛选设备状态"  @change="handleStatusChange" >
            <el-option
                v-for="(item, key) in statusselectMap"
                :key="key"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-col>

        <el-col :span="6" :offset="4" style="text-align: right">
          <el-button type="primary" icon="el-icon-plus" @click="handleCreateDevice">
            新增设备
          </el-button>
<!--          <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete"-->
<!--                     :disabled="selectedDeviceIds.length === 0" style="margin-left: 10px;">-->
<!--            批量删除-->
<!--          </el-button>-->
        </el-col>
      </el-row>
    </el-card>

    <!-- 设备表格 -->
    <el-card class="device-table-card"  default-align="center">
      <el-table
          fit show-overflow-tooltip
          :data="deviceList"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"

          v-loading="loading">

        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="设备ID" width="80"  align="center" header-align="center"></el-table-column>
        <el-table-column prop="deviceCode" width="80" label="设备代码" align="center" header-align="center"></el-table-column>
        <el-table-column prop="deviceName" width="100" label="设备名称" align="center" header-align="center"></el-table-column>

        <el-table-column prop="typeId" width="100" label="设备类型" align="center" header-align="center">
          <template #default="scope">
            {{ deviceTypeMap[scope.row.typeId] || scope.row.typeId}}
          </template>
        </el-table-column>

        <el-table-column prop="voltageLevel" width="100" label="电压等级" align="center" header-align="center"></el-table-column>

        <el-table-column prop="location" label="安装位置" align="center" header-align="center"></el-table-column>

        <el-table-column prop="status" label="状态" width="70">
          <template #default="scope">
            <!-- 1. 给标签添加点击事件，传入当前行数据和状态列表 -->
            <!-- 2.鼠标变成手型，提示可点击 -->
            <el-tag
                :type="statusMap[scope.row.status].type"
                @click="toggleStatus(scope.row, [0, 1, 2])"

                style="cursor: pointer;"
            >
            {{ statusMap[scope.row.status].label }}
            </el-tag>
          </template>
        </el-table-column>


        <el-table-column prop="createTime" label="创建时间" width="160">
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" header-align="center">
          <template #default="scope">

            <el-button size="mini" type="warning" @click="handleEditDevice(scope.row)">
              编辑
            </el-button>
<!--            <el-button size="mini" type="danger" @click="handleDeleteDevice(scope.row)">-->
<!--              删除-->
<!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页控件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
    </el-pagination>

    <!-- 编辑弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="设备信息"  width="60%">
      <el-form :model="currentDevice" label-width="120px">
        <el-form-item label="设备ID">
          <el-input v-model="currentDevice.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="设备代码">
          <el-input v-model="currentDevice.deviceCode" :disabled="dialogType === 'view'"></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="currentDevice.deviceName" :disabled="dialogType === 'view'"></el-input>
        </el-form-item>
<!--        <el-form-item label="设备类型">-->
<!--          <el-input v-model="currentDevice.typeId" :disabled="dialogType === 'view'"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="设备类型">
          <el-select

              v-model="currentDevice.typeId"
              :disabled="dialogType === 'view'"
              placeholder="请选择设备类型"
          >
            <el-option
                v-for="(item, index) in deviceTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="电压等级">
          <el-input v-model="currentDevice.voltageLevel" :disabled="dialogType === 'view'"></el-input>
        </el-form-item>
        <el-form-item label="安装位置">
          <el-input v-model="currentDevice.location" :disabled="dialogType === 'view'"></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
              v-model="currentDevice.status"
              :disabled="dialogType === 'view'"
              placeholder="请选择设备类型"
          >
            <el-option
                v-for="(item, index) in statusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 其他表单字段... -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveDevice()" v-if="dialogType !== 'view'">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {api} from "@/api";

export default {
  data() {
    return {
      searchType: 'name', // 新增，默认按名称搜索，可选 'name'（名称）、'id'（ID）

      // 表格数据
      deviceList: [],
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,

      // 搜索与筛选
      searchQuery: '',
      statusFilter: 1,

      // 选中的设备ID
      selectedDeviceIds: [],

      // 定义设备类型选项
      deviceTypeOptions: [
        { value: 1, label: '变压器' },
        { value: 2, label: '断路器' },
        { value: 3, label: '继电器' },
        { value: 4, label: '电容器' },
          { value: 5, label: '其他设备' },
        // 更多设备类型...
      ],

      // 设备类型映射表
      deviceTypeMap: {
        1: '变压器',
        2: '断路器',
        3: '继电器',
        4: '电容器',
        5: '其他设备',
        // 添加更多设备类型...
      },

      // 弹窗状态
      dialogVisible: false,
      dialogType: 'view', // 'view' | 'edit' | 'create'
      currentDevice: {},
// 状态映射：label（显示） → value（数据库存储）
      statusselectMap: {
        all: { label: '全部', value: '' },
        online: { label: '在线', value: 1 },
        offline: { label: '离线', value: 0 },
        fault: { label: '故障', value: 2 }
      },

      // 定义设备类型选项
      statusOptions: [
        { value: 1, label: '在线' },
        { value: 0, label: '离线' },
        { value: 2, label: '故障' },


      ],



      // 状态映射
      statusMap: {
        0: {label: '离线', type: 'danger'},   // 0 → 红色“离线”
        1: {label: '在线', type: 'success'},  // 1 → 绿色“在线”
        2: {label: '故障', type: 'warning'},  // 2 → 黄色“故障”
      }
    }
  },

  created() {
    this.fetchDeviceList();
  },

  methods: {

    // 状态改变时自动查询
    handleStatusChange() {
      this.currentPage = 1; // 重置页码到第1页
      this.fetchDeviceList(); // 重新获取设备列表（包含状态筛选）
    },


    toggleStatus(row, statusList) {
      // 2. 获取当前状态在列表中的索引
      const currentIndex = statusList.indexOf(row.status);

      // 3. 计算下一个状态的索引（循环切换）
      const nextIndex = (currentIndex + 1) % statusList.length;

      // 4. 更新行数据中的状态值
      row.status = statusList[nextIndex];

      // 5. 如果需要保存到服务器，可以在这里调用API
        this.updateDeviceStatus(row.id, row.status);
    },

    // 更新设备状态到服务器
    updateDeviceStatus(id, status) {
      const data = {
        id: id,
        status: status
      };
      return api.device.updatestatus(data)
          .then(() => {

          })
          .catch(error => {
            this.$message.error('状态更新失败：' + error.message);
            throw error; // 抛出错误以便上层处理
          });
    },

    // 获取设备列表
    fetchDeviceList() {
      this.loading = true;

      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
        status: this.statusFilter // 传递状态筛选参数

      }
      if (this.searchType === 'name') {
        params.searchQuery = this.searchQuery;
      } else {
        params.deviceId = this.searchQuery; // 假设后端接收设备ID搜索的参数是 deviceId
      }

      api.device.list(params)
          .then(response => {
            this.deviceList = response.data.records;
            this.totalCount = response.data.total;
            this.loading = false;
          })
          .catch(error => {
            console.error(error);
            this.$message.error('获取设备列表失败');
            this.loading = false;
          });
    },

    // 搜索设备
    handleSearch() {
      this.currentPage = 1;
      this.fetchDeviceList();
    },

    // 分页相关
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchDeviceList();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchDeviceList();
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedDeviceIds = selection.map(item => item.id);
    },


    // 编辑设备
    handleEditDevice(device) {
      this.currentDevice = {...device};
      this.dialogType = 'edit';
      this.dialogVisible = true;
    },

    // 新增设备
    handleCreateDevice() {
      this.currentDevice = {};
      this.dialogType = 'create';
      this.dialogVisible = true;
    },

    //保存设备（编辑）
    handleSaveDevice() {

      api.device.update(this.currentDevice)
          .then(() => {
            this.$message.success('更新设备成功');
            this.dialogVisible = false;
            this.fetchDeviceList();
          }).catch(error => {
        if (error.response) {
          // 服务器返回了错误响应
          this.$message.error(`编辑设备失败: ${error.response.data.message || '服务器错误'}`);
        } else if (error.request) {
          // 请求已发送，但没有收到响应
          this.$message.error('编辑设备失败: 没有收到服务器响应');
        } else {
          // 其他错误
          this.$message.error(`编辑设备失败: ${error.message}`);
        }
      })

    },


    // 删除单个设备
    // handleDeleteDevice(device) {
    //   this.$confirm(`确定删除设备 ${device.deviceName} 吗？`, '提示', {
    //     type: 'warning'
    //   }).then(() => {
    //
    //     api.device.remove(device.id)
    //         .then(() => {
    //           this.$message.success('删除设备成功');
    //           this.fetchDeviceList();
    //         })
    //         .catch(error => {
    //           console.error(error);
    //           this.$message.error('删除设备失败');
    //         });
    //   }).catch(() => {
    //     // 用户取消操作
    //   });
    // },

    // 批量删除设备
    handleBatchDelete() {
      if (this.selectedDeviceIds.length === 0) {
        this.$message.warning('请先选择要删除的设备');
        return;
      }

      this.$confirm(`确定删除选中的 ${this.selectedDeviceIds.length} 个设备吗？`, '提示', {
        type: 'warning'
      }).then(() => {

        api.device.batchDelete(this.selectedDeviceIds)
          .then(() => {
            this.$message.success('批量删除设备成功');
            this.fetchDeviceList();
            this.selectedDeviceIds = [];
          })
          .catch(error => {
            console.error(error);
            this.$message.error('批量删除设备失败');
          });
      }).catch(() => {
        // 用户取消操作
      });
    }
  }
}
</script>

<style scoped>
.device-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.device-table-card {
  margin-bottom: 20px;
}
</style>